﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;

namespace VSM
{
    public partial class InventoryTransferRequest : System.Web.UI.Page
    {
        #region Fields
        public static DataTable dtContents;
        public static DataTable dtHeader;
        private static GeneralFunctions GF = null;

        private string TblHeaderName = "OWTQ";
        private string TblLineName = "WTQ1";
        private string HeaderKeyName = "DocEntry";
        private string CurrentPageUrl = "/Business/Inventory/InventoryTransferRequest.aspx";
        private String TargetPageUrl = "/Business/Inventory/InventoryTransfer.aspx";
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.Private);

            if (Session[Utils.AppConstants.ID_User] == null
                || Session[Utils.AppConstants.Password] == null
                || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("../../Login.aspx");
            }

            if (!IsPostBack)
            {
                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                ClearScreen();


                String itransRqstId = Request.QueryString["itransrqst_id"];
                if (!String.IsNullOrEmpty(itransRqstId))
                {
                    LoadData(itransRqstId, ConvertDocType.Get2String(DocType.TRANSFER_REQUEST));
                    if (lblStatus.Text == "Closed")
                        SetScreenStatus("Close");
                    else if (lblStatus.Text == "OPen")
                        SetScreenStatus("Update");
                }
                else
                {
                    LoadDefault();
                    SetScreenStatus("New");
                }
            } 
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvWTQ1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvWTQ1.PageIndex = e.NewPageIndex;
            DataTable tblWTQ1 = (DataTable)Session["WTQ1RqstTable"];
            BindData(tblWTQ1);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tblITransRqst = (DataTable)Session["WTQ1RqstTable"];

                if (tblITransRqst != null)
                {
                    DataRow[] rupdate = tblITransRqst.Select("No=" + lblNo.Text );
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString())) dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                        }
                        tblITransRqst.Rows.Remove(rupdate[0]);
                        int liNo = 1;
                        foreach (DataRow dr in tblITransRqst.Rows) // reset detail No. line
                        {
                            dr["No"] = liNo;
                            liNo++;
                        }
                    }
                    this.grvWTQ1.EditIndex = -1;
                    BindData((DataTable)Session["WTQ1RqstTable"]);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvWTQ1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";

                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                // Load Model
                DropDownList ddlModel = (DropDownList)e.Row.FindControl("ddlModel");
                HiddenField hdnModel = (HiddenField)e.Row.FindControl("hdnModel");
                if (ddlModel != null)
                {
                    ddlModel.DataSource = GF.GetModelList(dbType);
                    ddlModel.DataValueField = "Code";
                    ddlModel.DataTextField = "Name";
                    ddlModel.DataBind();
                    ddlModel.Items.Insert(0, "");
                    if (hdnModel != null) ddlModel.SelectedValue = hdnModel.Value;
                }
                // Load Product
                DropDownList ddlProduct = (DropDownList)e.Row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, hdnModel.Value);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");
                    HiddenField hdnProduct = (HiddenField)e.Row.FindControl("hdnProduct");
                    if (hdnProduct != null) ddlProduct.SelectedValue = hdnProduct.Value;
                }
                // Load Color
                DropDownList ddlColor = (DropDownList)e.Row.FindControl("ddlColor");
                if (ddlColor != null)
                {
                    ddlColor.DataSource = GF.GetColorList(dbType);
                    ddlColor.DataValueField = "Code";
                    ddlColor.DataTextField = "Name";
                    ddlColor.DataBind();
                    ddlColor.Items.Insert(0, "");
                    HiddenField hdnColor = (HiddenField)e.Row.FindControl("hdnColor");
                    if (hdnColor != null) ddlColor.SelectedValue = hdnColor.Value;
                }

            }
        }
  
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tblITransRqst = (DataTable)Session["WTQ1RqstTable"];
                if (tblITransRqst != null)
                {
                    DataRow[] rupdate = tblITransRqst.Select("No=" + lblNo.Text );
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = GF.FormatNumeric( GF.ResetFormatNumeric(txtQuantity.Text), "QtyDec");
                    }
                }

                this.grvWTQ1.EditIndex = -1;

                BindData(tblITransRqst);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            Session["WTQ1RqstTable"] = tblData;
            this.grvWTQ1.DataSource = tblData;
            this.grvWTQ1.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text.Trim());
                    DataTable tblITransRqst = (DataTable)Session["WTQ1RqstTable"];
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    GridViewRow grdvRow = null;

                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectItem":
                            this.lblError.Visible = false;
                            if (tblITransRqst != null)
                            {
                                Dictionary<string, string> dicItem = Session["ChosenItem"] != null ? (Dictionary<string, string>)Session["ChosenItem"] : null;
                                if (dicItem != null)
                                {
                                    foreach (KeyValuePair<string, string> item in dicItem)
                                    {
                                        DataRow rowNew = tblITransRqst.NewRow();
                                        rowNew["No"] = (tblITransRqst.Rows.Count + 1).ToString();
                                        rowNew["ItemCode"] = item.Key;
                                        rowNew["Dscription"] = item.Value;
                                        rowNew["U_Model"] =
                                        rowNew["U_Product"] =
                                        rowNew["U_Color"] = string.Empty;
                                        rowNew["Quantity"] = 1;
                                        rowNew["FromWhsCod"] = txtFromWhsCode.Text.Trim();
                                        rowNew["WhsCode"] = txtToWhsCode.Text.Trim();
                                        tblITransRqst.Rows.Add(rowNew);
                                    }
                                }
                            }
                            //ReLoad Data
                            BindData(tblITransRqst);
                            break;

                        case "SelectBP":
                            ViewState["rowindex"] = -1;
                            this.lblError.Visible = false;
                            grdvRow = Session["ChosenBP"] != null ? (GridViewRow)Session["ChosenBP"] : null;

                            this.txtCustomerCode.Text = ((Label)grdvRow.FindControl("lblCardCode")).Text;
                            this.txtCustomerName.Text = ((Label)grdvRow.FindControl("lblCardName")).Text;
                            this.txtContactPerson.Text = ((Label)grdvRow.FindControl("lblCntctPrsn")).Text;

                            if (tblITransRqst != null) tblITransRqst.Rows.Clear();
                            Session["ChosenBP"] = null;
                            this.btnAddAccessories.Enabled =
                            this.btnAddItems.Enabled = true;
                            break;

                        case "SelectWhsFrom":
                            this.lblError.Visible = false;
                            grdvRow = Session["ChosenWhs"] != null ? (GridViewRow)Session["ChosenWhs"] : null;
                            this.txtFromWhsCode.Text = ((Label)grdvRow.FindControl("lblWhsCode")).Text;
                            this.txtFromWhsName.Text = ((Label)grdvRow.FindControl("lblWhsName")).Text;

                            Session["ChosenWhs"] = null;
                            break;

                        case "SelectWhsTo":
                            this.lblError.Visible = false;
                            grdvRow = Session["ChosenWhs"] != null ? (GridViewRow)Session["ChosenWhs"] : null;
                            this.txtToWhsCode.Text = ((Label)grdvRow.FindControl("lblWhsCode")).Text;
                            this.txtToWhsName.Text = ((Label)grdvRow.FindControl("lblWhsName")).Text;
                            Session["ChosenWhs"] = null;
                            break;

                        case "SelectDocList":
                            GridViewRow rowDocList = Session["ChosenDocList"] != null ? (GridViewRow)Session["ChosenDocList"] : null;
                            string DocEntry = ((Label)rowDocList.FindControl("lblDocNum")).Text;
                            string doctype = ((Label)rowDocList.FindControl("lblDocType")).Text;
                            LoadData(DocEntry, doctype);
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        //private DataTable AddNewItem(DataTable tblITransRqst, DataRow drDefaultLine, string ItemCode, string Dscription, string Model, string Color)
        //{
        //    try
        //    {
        //        if (drDefaultLine != null && drDefaultLine.ItemArray.Length > 0)
        //        {
        //            DataRow rowNew = tblITransRqst.NewRow();
        //            rowNew["No"] = (tblITransRqst.Rows.Count + 1).ToString();
        //            rowNew["ItemCode"] = ItemCode;
        //            rowNew["Dscription"] = Dscription;
        //            rowNew["U_Model"] = Model;
        //            rowNew["U_Color"] = Color;
        //            rowNew["Quantity"] = 1;

        //            rowNew["FromWhsCod"] = txtFromWhsCode.Text;
        //            rowNew["WhsCode"] = txtToWhsCode.Text;

        //            DataRow[] rCheck = tblITransRqst.Select("ItemCode='" + ItemCode + "'");
        //            if (rCheck.Length == 0)
        //            {
        //                tblITransRqst.Rows.Add(rowNew);
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        this.lblError.Text = ex.Message;
        //        this.lblError.Visible = true;
        //    }
        //    return tblITransRqst;
        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="poDate"></param>
        /// <param name="itemCode"></param>
        /// <param name="venderCode"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        //private DataSet GetDataItem(DateTime poDate, string itemCode, string venderCode, double quantity)
        //{
        //    try
        //    {
        //        MasterData obj = new MasterData();
        //        DataSet ds = new DataSet();
        //        ds = null; // obj.GetItem(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode, poDate, itemCode, venderCode, quantity);
        //        return ds;
        //    }
        //    catch (Exception ex)
        //    {
        //        this.lblError.Text = ex.Message;
        //        this.lblError.Visible = true;
        //    }
        //    return null;
        //}

        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvWTQ1_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();

                if (this.hdnStatus.Value == "C")
                {
                    DropDownList ddlModel = (DropDownList)myRow.FindControl("ddlModel");
                    DropDownList ddlProduct = (DropDownList)myRow.FindControl("ddlProduct");
                    DropDownList ddlColor = (DropDownList)myRow.FindControl("ddlColor");
                    TextBox txtQuantity = (TextBox)myRow.FindControl("txtQuantity");

                    if (ddlModel != null)
                    {
                        ddlModel.Enabled = false;
                        ddlModel.BackColor = System.Drawing.Color.Transparent;
                        ddlModel.BorderStyle = BorderStyle.None;
                    }

                    if (ddlProduct != null)
                    {
                        ddlProduct.Enabled = false;
                        ddlProduct.BackColor = System.Drawing.Color.Transparent;
                        ddlProduct.BorderStyle = BorderStyle.None;
                    }

                    if (ddlColor != null)
                    {
                        ddlColor.Enabled = false;
                        ddlColor.BackColor = System.Drawing.Color.Transparent;
                        ddlColor.BorderStyle = BorderStyle.None;
                    }

                    if (txtQuantity != null)
                    {
                        txtQuantity.ReadOnly = true;
                        txtQuantity.BackColor = System.Drawing.Color.Transparent;
                        txtQuantity.BorderStyle = BorderStyle.None;
                    }
                }
            }
        }

        protected void ddlModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
                if (ddlModel.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Model');", true);
                    ddlModel.Focus();
                    return;
                }
                HiddenField hdnModel = (HiddenField)row.FindControl("hdnModel");
                hdnModel.Value = ddlModel.SelectedValue;

                // Load Product
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, ddlModel.SelectedValue);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");

                    HiddenField hdnProduct = (HiddenField)row.FindControl("hdnProduct");
                    hdnProduct.Value = ddlProduct.SelectedValue;
                    SetItem(row);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Product');", true);
                    ddlProduct.Focus();
                    return;
                }

                HiddenField hdnProduct = (HiddenField)row.FindControl("hdnProduct");
                hdnProduct.Value = ddlProduct.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlColor_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlColor = (DropDownList)row.FindControl("ddlColor");
                if (ddlColor.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Color');", true);
                    ddlColor.Focus();
                    return;
                }

                HiddenField hdnColor = (HiddenField)row.FindControl("hdnColor");
                hdnColor.Value = ddlColor.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        private void SetItem(GridViewRow row)
        {
            DataTable tblWTQ1 = (DataTable)Session["WTQ1RqstTable"];
            Label lblNo = (Label)row.FindControl("lblNo");
            DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
            DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
            DropDownList ddlCorlor = (DropDownList)row.FindControl("ddlColor");

            if (ddlModel != null && ddlProduct != null && ddlCorlor != null)
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                DataTable dtItem = GF.GetItem(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlModel.SelectedValue, ddlProduct.SelectedValue, ddlCorlor.SelectedValue);
                GetDefault defaultWS = new GetDefault();
                DataRow[] rowUpdate = null;
                if (dtItem != null && dtItem.Rows.Count == 1)
                {
                    DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                    DataSet defaultInfo = defaultWS.GetDefaultLineInfo(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(),
                        this.txtCustomerCode.Text, dtItem.Rows[0]["ItemCode"].ToString(), 1, poDate, Utils.AppConstants.SALES);
                    if (defaultInfo != null && defaultInfo.Tables != null && defaultInfo.Tables[0].Rows.Count == 1)
                    {
                        DataRow drDefaultLine = defaultInfo.Tables[0].Rows[0];
                        rowUpdate = tblWTQ1.Select("No=" + lblNo.Text);
                        if (rowUpdate.Length == 1)
                        {
                            rowUpdate[0]["ItemCode"] = dtItem.Rows[0]["ItemCode"].ToString();
                            rowUpdate[0]["Dscription"] = dtItem.Rows[0]["ItemName"].ToString();
                            rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                            rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                            rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                            rowUpdate[0]["Quantity"] = 1;
                        }
                    }
                }
                else
                {
                    rowUpdate = tblWTQ1.Select("No=" + lblNo.Text);
                    rowUpdate[0]["ItemCode"] =
                    rowUpdate[0]["Dscription"] = string.Empty;
                    rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                    rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                    rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                    rowUpdate[0]["Quantity"] = 1;
                }
                BindData(tblWTQ1);
                
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtPODate_TextChanged(object sender, EventArgs e)
        {
            try
            {
                //Check Valid Date
               Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text.Trim());
               this.btnAddItems.Enabled = true;
            }
            catch
            {
                this.btnAddItems.Enabled = false;
            }
        }
        /// <summary>
        /// 
        /// </summary>
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {

                if (string.IsNullOrEmpty(txtPostingDate.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Posting Date.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    return;
                }

                if (string.IsNullOrEmpty(txtDocDate.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Document Date.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    return;
                }

                if (string.IsNullOrEmpty(txtDueDate.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Due Date.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    return;
                }

                if (string.IsNullOrEmpty(txtCustomerCode.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Customer Code.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    return;
                }

                if (string.IsNullOrEmpty(txtFromWhsCode.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing From Warehouse Code.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    return;
                }

                if (string.IsNullOrEmpty(txtToWhsCode.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing To Warehouse Code.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    return;
                }

                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                String requestXML = _collectData();
                if (requestXML == "") return;

                Transaction ts = new Transaction();
                DataSet ds = ts.CreateMarketingDocument(requestXML, ((ulong)DocType.TRANSFER).ToString(), txtTransferRqstNo.Text, hdnIsUpdate.Value.Equals("true"), dbType);

                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                //SetControlsStatus("Save");
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseCancel(true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
            CloseCancel(false);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isClose"></param>
        private void CloseCancel(bool isClose)
        {
            try
            {
                Transaction ts = new Transaction();
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM) ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                DataSet ds = ts.CloseCancelDocument(ConvertDocType.Get2String(DocType.TRANSFER_REQUEST), txtTransferRqstNo.Text, isClose, dbType);

                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }

        public String _collectData()
        {
            try
            {
                //Update table header
                DataTable dtHeader = new DataTable("OWTQ");
                dtHeader.Columns.Add("DocEntry");
                dtHeader.Columns.Add("DocNum");
                dtHeader.Columns.Add("Series"); // 45
                dtHeader.Columns.Add("DocStatus");
                dtHeader.Columns.Add("DocDate");
                dtHeader.Columns.Add("DocDueDate");
                dtHeader.Columns.Add("TaxDate");
                dtHeader.Columns.Add("CardCode");
                dtHeader.Columns.Add("CardName");
                dtHeader.Columns.Add("Comments");
                dtHeader.Columns.Add("Filler");
                dtHeader.Columns.Add("ToWhsCode");
                // UDF
                dtHeader.Columns.Add("U_ContactPerson");
                dtHeader.Columns.Add("U_DealerID");
                dtHeader.Columns.Add("U_Department");
                dtHeader.Columns.Add("U_SOType");
                DataRow drHeader = dtHeader.NewRow();
                if (hdnIsUpdate.Value.Equals("true"))
                {
                    drHeader["DocEntry"] =
                    drHeader["DocNum"] = int.Parse(txtTransferRqstNo.Text);
                }
                else
                    drHeader["Series"] = 45;

                drHeader["DocStatus"] = "O";
                drHeader["DocDate"] = Utils.AppConstants.ConvertToDate(txtPostingDate.Text).ToString("yyyyMMdd");
                drHeader["DocDueDate"] = Utils.AppConstants.ConvertToDate(txtDueDate.Text).ToString("yyyyMMdd");
                drHeader["TaxDate"] = Utils.AppConstants.ConvertToDate(txtDocDate.Text).ToString("yyyyMMdd");
                drHeader["Comments"] = txtRemarks.Text;
                //dr["JrnlMemo"] = txtJournalRemark.Text;
                drHeader["CardCode"] = txtCustomerCode.Text;
                drHeader["CardName"] = txtCustomerName.Text;
                
                drHeader["Filler"] = txtFromWhsCode.Text;
                drHeader["ToWhsCode"] = txtToWhsCode.Text;
                // UDF
                drHeader["U_SOType"] = "0";
                drHeader["U_ContactPerson"] = txtContactPerson.Text.Trim();
                drHeader["U_DealerID"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                drHeader["U_Department"] = Utils.AppConstants.SALES;
                
                dtHeader.Rows.Add(drHeader);
                
                DataSet ds = new DataSet("DS");
                dtHeader.TableName = TblHeaderName;
                dtContents.TableName = TblLineName;
                ds.Tables.Add(dtHeader.Copy());

                DataTable dt = new DataTable("WTQ1");
                dt.Columns.Add("DocEntry");
                dt.Columns.Add("LineNum");
                dt.Columns.Add("ItemCode");
                dt.Columns.Add("Dscription");
                dt.Columns.Add("U_Model");
                dt.Columns.Add("U_Product");
                dt.Columns.Add("U_Color");
                dt.Columns.Add("FromWhsCod");
                dt.Columns.Add("WhsCode");
                dt.Columns.Add("Quantity");
                dt.Columns.Add("UomCode");

                int liNo = 0;
                foreach (DataRow dr in dtContents.Rows)
                {
                    DataRow rowNew = dt.NewRow();
                    if (hdnIsUpdate.Value.Equals("true")) rowNew["DocEntry"] = int.Parse(txtTransferRqstNo.Text);
                    rowNew["LineNum"] = liNo;
                    rowNew["ItemCode"] = dr["ItemCode"];
                    rowNew["Dscription"] = dr["Dscription"];
                    rowNew["U_Model"] = dr["U_Model"];
                    rowNew["U_Product"] = dr["U_Product"];
                    rowNew["U_Color"] = dr["U_Color"];
                    rowNew["FromWhsCod"] = txtFromWhsCode.Text;
                    rowNew["WhsCode"] = txtToWhsCode.Text;
                    rowNew["Quantity"] = dr["Quantity"];
                    rowNew["UomCode"] = dr["UomCode"];

                    dt.Rows.Add(rowNew);
                    liNo++;
                }

                ds.Tables.Add(GF.ResetFormatNumeric(dt, new string[] { "Quantity" }).Copy());
                DocumentXML objInfo = new DocumentXML();
                return objInfo.ToXMLStringFromDS(ConvertDocType.Get2String(DocType.TRANSFER_REQUEST), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }

        private DataTable BuildContents(DataTable dtContent)
        {
            DataTable dt = new DataTable("WTQ1");
            dt.Columns.Add("No");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Dscription");

            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Product");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("UomCode");
            dt.Columns.Add("Quantity");

            dt.Columns.Add("FromWhsCod");
            dt.Columns.Add("WhsCode");

            dt.Columns.Add("DocEntry");
            dt.Columns.Add("LineNum");

            if (dtContent != null)
            {
                foreach (DataRow dr in dtContent.Rows)
                {
                    DataRow row = dt.NewRow();
                    row["No"] = dr["No"];
                    row["ItemCode"] = dr["ItemCode"];
                    row["Dscription"] = dr["Dscription"];
                    row["U_Model"] = dr["U_Model"];
                    row["U_Product"] = dr["U_Product"];
                    row["U_Color"] = dr["U_Color"];
                    row["UomCode"] = dr["UomCode"];
                    row["Quantity"] = GF.FormatNumeric(GF.ResetFormatNumeric(dr["Quantity"].ToString()), "QtyDec");

                    row["FromWhsCod"] = dr["FromWhsCod"];
                    row["WhsCode"] = dr["WhsCode"]; // To Whs Code
                    row["DocEntry"] = dr["DocEntry"];
                    row["LineNum"] = dr["LineNum"];
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }

        protected void LoadData(String itransRqstId, string NewDocType)
        {

            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            Transaction ts = new Transaction();

            DataSet returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, itransRqstId, dbType);

            if (returnDoc == null)
                itransRqstId = "1";
            else
                dtHeader = returnDoc.Tables[0];

            returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, itransRqstId, dbType);

            if (returnDoc == null || returnDoc.Tables.Count < 2)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('No record found!','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return;
            }

            dtHeader = returnDoc.Tables[0];
            dtContents = BuildContents(returnDoc.Tables[1]);
            DataRow dr = dtHeader.Rows[0];

            this.txtTransferRqstNo.Text = dr["DocNum"].ToString();
            this.txtCustomerCode.Text = dr["CardCode"].ToString();
            this.txtCustomerName.Text = dr["CardName"].ToString();
            this.txtFromWhsCode.Text = dr["Filler"].ToString();
            this.txtToWhsCode.Text = dr["ToWhsCode"].ToString();

            txtDueDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDueDate"], new CultureInfo("es-US")));
            txtPostingDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDate"], new CultureInfo("es-US")));
            txtDocDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["TaxDate"], new CultureInfo("es-US")));
            txtRemarks.Text = dr["Comments"].ToString();


            if (dr["DocStatus"].ToString().Equals("C"))
            {
                this.lblStatus.Text = "Closed";
                SetScreenStatus("Close");
            }
            else if (dr["DocStatus"].ToString().Equals("O"))
            {
                this.lblStatus.Text = "Open";
                SetScreenStatus("Update");

            }

            BindData(dtContents);
        }

        protected void LoadDefault()
        {
            this.txtPostingDate.Text =
            this.txtDocDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtTransferRqstNo.Text =
            this.txtCustomerCode.Text =
            this.txtCustomerName.Text = 
            this.txtContactPerson.Text = string.Empty;
            
            dtContents = BuildContents(dtContents);
            BindData(dtContents);
        }

        protected void ClearScreen()
        {
            CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
            txtPostingDate.Text.ToString(ci);
            txtDueDate.Text.ToString(ci);
            txtDocDate.Text.ToString(ci);
            txtCustomerCode.Text =
            txtCustomerName.Text =
            txtRemarks.Text = 
            txtContactPerson.Text = string.Empty;

            dtContents = new DataTable("WTR1");
            dtContents.Columns.Add("LineNum");
            dtContents.Columns.Add("LineStatus");
            dtContents.Columns.Add("ItemCode");
            dtContents.Columns.Add("Dscription");
            dtContents.Columns.Add("FromWhsCod");
            dtContents.Columns.Add("U_Model");
            dtContents.Columns.Add("U_Product");
            dtContents.Columns.Add("U_Color");
            dtContents.Columns.Add("WhsCode");
            dtContents.Columns.Add("Quantity");
            dtContents.Columns.Add("UomCode");
            BindData(dtContents);
            SetScreenStatus("New");
        }

        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    btnPrint.Enabled =
                    btnAddItems.Enabled = false;
                    btnLastRecord.Enabled =
                    btnSave.Enabled = 
                    btnCopyTo.Enabled = 
                    btnCancel.Enabled = true;
                    hdnIsUpdate.Value = "false";
                    hdnStatus.Value = "O";
                    break;

                case "Update":
                    btnLastRecord.Enabled =
                    btnPrint.Enabled =
                    btnAddItems.Enabled = 
                    btnSave.Enabled = 
                    btnCancel.Enabled = 
                    btnCopyTo.Enabled = true;
                    hdnIsUpdate.Value = "true";
                    hdnStatus.Value = "O";
                    break;

                case "Close":
                    btnLastRecord.Enabled =
                    btnPrint.Enabled = true;
                    btnAddItems.Enabled = 
                    btnSave.Enabled = 
                    btnCopyTo.Enabled = 
                    btnCancel.Enabled = false;
                    hdnStatus.Value = "C";
                    break;
            }
        }

        protected void btnCopyTo_Click(object sender, EventArgs e)
        {
            Response.Redirect(TargetPageUrl + "?base_type=" + ConvertDocType.Get2String(DocType.TRANSFER_REQUEST) + "&base_entry=" + txtTransferRqstNo.Text);
        }

        protected void btnAddItems_Click(object sender, EventArgs e)
        {
            DataTable tbWTQ1 = (DataTable)Session["WTQ1RqstTable"];
            DataRow rowNew = tbWTQ1.NewRow();
            rowNew["No"] = (tbWTQ1.Rows.Count + 1).ToString();
            rowNew["ItemCode"] =
            rowNew["Dscription"] =
            rowNew["U_Model"] =
            rowNew["U_Product"] =
            rowNew["U_Color"] = string.Empty;
            rowNew["Quantity"] = 1;
            rowNew["FromWhsCod"] = txtFromWhsCode.Text.Trim();
            rowNew["WhsCode"] = txtToWhsCode.Text.Trim();

            tbWTQ1.Rows.Add(rowNew);
            BindData(tbWTQ1);
        }

        protected void btnLastRecord_Click(object sender, EventArgs e)
        {
            GetDefault fGetDefault = new GetDefault();
            string lsTrsRqstNo = fGetDefault.GetMaxDocEntry(
                Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER,
                Session[Utils.AppConstants.ID_Dealer].ToString(),
                Utils.AppConstants.SALES,
                ConvertDocType.Get2String(DocType.TRANSFER_REQUEST),
                TblHeaderName, HeaderKeyName
            );
            if (txtTransferRqstNo.Text.CompareTo(lsTrsRqstNo) != 0) Response.Redirect(CurrentPageUrl + "?itransrqst_id=" + lsTrsRqstNo);
        }
    }
}